<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * @property Threads $threads
 */
class Demo_mysql extends CI_Controller
{

	private static $server;

	public function __construct()
	{
		parent::__construct();
		self::$server = websocket_server_open();
		$this->load->model('demo/threads');
	}

	/**
	 * SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
	 * SET time_zone = "+00:00";
	 *
	 * --
	 * -- Database: `oschina`
	 * --
	 *
	 * -- --------------------------------------------------------
	 *
	 * --
	 * -- 表的结构 `server_options`
	 * --
	 *
	 * CREATE TABLE `server_options` (
	 * `name` varchar(25) COLLATE utf8_bin NOT NULL,
	 * `value` varchar(100) COLLATE utf8_bin DEFAULT NULL
	 * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
	 *
	 * --
	 * -- 转存表中的数据 `server_options`
	 * --
	 *
	 * INSERT INTO `server_options` (`name`, `value`) VALUES
	 * ('description', '描述'),
	 * ('keywords', '关键字1, 关键字2'),
	 * ('site_name', '网站标题');
	 */
	public function index()
	{

		self::$server->on('open', function (swoole_websocket_server $server, swoole_http_request $request) {
			//
		});

		self::$server->on('message', function (swoole_websocket_server $server, $frame) {
			if ($frame->data == 'hello') {
				$this->threads->async_mysql(
					"SELECT * FROM `client_options` ORDER BY `name` DESC",
					function ($db, $result) use ($server, $frame) {
						var_dump($result, $db->affected_rows, $db->insert_id); // 结果集、影响行数、自增ID（如果是 insert 的话）
						if (!empty($result)) $server->push($frame->fd, json_encode($result));
					}
				);
			}
		});

		/*self::$server->on('task', function (swoole_websocket_server $server, $task_id, $src_worker_id, $data) {
			//
		});

		self::$server->on('finish', function (swoole_websocket_server $server, $task_id, $result) {
			//
		});*/

		echo "server " . self::$server->host . ':' . self::$server->port . " is running" . PHP_EOL;


		self::$server->start();
	}

}